/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package talkunix;
import java.io.*;
import java.lang.Runnable;
import java.net.*;
import talkunix.DeamonOuvir;
/**
 *
 * @author Administrador
 */
public class Secao {
    public static ServerSocket Deamon;
    public  static Socket DeamonSocket = null;
    private Socket DeamonCliente = null;
    private Socket Cliente;
//    private DataOutputStream os = null;
    private static BufferedReader is;
    private static PrintWriter os;
//    private DataInputStream is = null;
    public static  boolean go = false;
    public  DeamonOuvir Ouvindo;
    public Thread Tentando;


    public  boolean getgo(){

        return go;
    }

    public  static void setgo(){
        go = true;
    }



    public Secao(){

    }

    public void Ouvir(int porta) throws IOException, InterruptedException{

//        Deamon = new ServerSocket(porta);
        System.out.println("Demon set");
//        DeamonSocket = Deamon.accept();
        Ouvindo = new DeamonOuvir(porta);
        Tentando = new Thread(Ouvindo);
        Tentando.start();
//        System.out.println("Socket set");

    }

    public static  void Abrir() throws IOException, InterruptedException{

//        while (Tentando.isAlive()){
//
//            Thread.sleep(1000);
//        }


        os = new PrintWriter(DeamonSocket.getOutputStream(), true);


        System.out.println("os set");
        // is = new DataInputStream(DeamonSocket.getInputStream());
        
        is = new BufferedReader(new InputStreamReader(DeamonSocket.getInputStream()));
        System.out.println("is set");
        ClienteServidor.conectado = true;


    }

    public void Conectar(String s,int p) throws UnknownHostException, IOException{
        
        Cliente = new Socket(s,p);
        System.out.println("Cliente");
//        os = new DataOutputStream(Cliente.getOutputStream());
        os = new PrintWriter(Cliente.getOutputStream(), true);
        System.out.println("os set ");
//        is = new DataInputStream(Cliente.getInputStream());
        is = new BufferedReader(new InputStreamReader(Cliente.getInputStream()));
        System.out.println("is set");




    }

    public void Enviar(String texto) throws IOException{

        System.out.println("enviando");

        os.println(texto);
        System.out.println("enviado");
    }

    public String Recebe() throws IOException{

        String linha;
        System.out.println("esperando o is");
        linha = is.readLine();
        System.out.println("leu o is");
        return linha;
    }

    public void Encerrar() throws IOException{
        os.close();
        is.close();
        try {

            Cliente.close();
        }
        finally{

        }
        try{

            Deamon.close();
        }
        finally{

        }



        
    }





}
